import React, {useState} from 'react';
import { Button, Form, Input, Upload, message, Modal } from 'antd';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { Scrollbars } from 'react-custom-scrollbars';

import style from './FeatureAdd.module.scss';

const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);

        reader.onload = () => resolve(reader.result);

        reader.onerror = (error) => reject(error);
});

const FeatureAdd = (props) => {
    const {fields, fieldNames, setAddShow, addFeature, addLoading} = props;

    const [form] = Form.useForm();

    const [loading, setLoading] = useState(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [fileList, setFileList] = useState([]);

    const onFinish = (values) => {
        const {images='', ...resetValues} = values;
        const newImages = getImages(images);
        
        const params = {
            temp: newImages,
            values: resetValues
        };
        addFeature(params);
    };

    const onCancel = () => {
        setAddShow(false);
    };

    // 解析图片
    const getImages = (images) => {
        if(!images) return null;
        let tempArr = [];
        const {fileList} = images;
        fileList.forEach(item => {
            const {response: {code, data}} = item;
            if(code === 200) {
                const {temp = ''} = data;
                temp && tempArr.push(temp);
            }
        });
        if(tempArr.length > 0){
            return tempArr.join(',');
        }else{
            return '';
        }
    };

    // 上传前图片校验
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

        if (!isJpgOrPng) {
            message.error('您只能上传 JPG 或 PNG 文件!');
        }

        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isLt2M) {
            message.error('图片大小不能超过 2MB!');
        }

        return isJpgOrPng && isLt2M;
    };

    // 图片移除
    const handleRemove = (file) => {
        const index = fileList.findIndex((item) => {
            return item.uid === file.uid;
        });
        let copyFileList = JSON.parse(JSON.stringify(fileList));
        if(index > -1){
            copyFileList.splice(index, 1);
        }
        setFileList(copyFileList);
    };

    // 图片预览
    const handlePreview = async (file) => {
        if(!file.originFileObj) return;
        
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
    
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    };

    // 图片上传
    const handleChange = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
      
        if (info.file.status === 'done') {
            const {file: {response}} = info;
            const {code} = response;
            if(code === 200){
                setFileList(info.fileList);
            }
            setLoading(false);
        }
    };

    const formItems = fields.map(field => {
        return (
            <Form.Item label={fieldNames[field] ? fieldNames[field] : field} name={field} key={field}>
                <Input />
            </Form.Item>
        )
    });

    const buttonItemLayout ={
        wrapperCol: {
            span: 14,
            offset: 8
        }
    };

    return ( 
        <div className={style.featureAdd}>
            <Scrollbars autoHeight autoHeightMin={0} autoHeightMax={`calc(100vh - 250px)`}>
                <Form
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 16 }}
                    layout="horizontal"
                    form={form}
                    onFinish={onFinish}
                >
                    {formItems}
                    <Form.Item label="图片" valuePropName="images" name="images">
                        <Upload 
                            action="/webapi/2.0/image/upload" 
                            listType="picture-card" 
                            fileList={fileList} 
                            beforeUpload={beforeUpload} 
                            onPreview={handlePreview}
                            onRemove={handleRemove}
                            onChange={handleChange}>
                                {
                                    fileList.length > 5 ? null : 
                                        <div>
                                            {loading ? <LoadingOutlined /> : <PlusOutlined />}
                                            <div style={{ marginTop: 8 }}>上传</div>
                                        </div>
                            }
                                
                        </Upload>
                    </Form.Item>
                    <Form.Item label="" {...buttonItemLayout}>
                        <Button type="primary" htmlType="submit" className={style.commit} loading={addLoading}>提交</Button>
                        <Button type="primary" onClick={onCancel}>取消</Button>
                    </Form.Item>
                </Form>
            </Scrollbars>
            
            <Modal visible={previewOpen} title={previewTitle} footer={null} onCancel={() => setPreviewOpen(false)}>
                <img
                    alt="example"
                    style={{
                        width: '100%',
                    }}
                    src={previewImage}
                />
            </Modal>
        </div>
    )
};

export default FeatureAdd;